package Middleware

import (
	"Student_Mental/controller/login"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"regexp"
	"time"
)

// Cotstime 耗时统计中间件
func Cotstime() gin.HandlerFunc {
	return func(c *gin.Context) {
		//session := sessions.Default(c)
		//请求前获取当前时间
		nowTime := time.Now()
		//请求处理
		c.Next()
		//处理后获取消耗时间
		costTime := time.Since(nowTime)
		url := c.Request.URL.String()
		fmt.Printf("the request URL %s cost %v\n", url, costTime)
	}
}

func in(url string, List []string) bool {
	for _, v := range List {
		if url == v {
			return true
		}
	}
	return false
}

// Cheaklogin 登入中间件
func Cheaklogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		Token, _ := c.Cookie("Token")
		Name, _ := c.Cookie("Name")
		Id, _ := c.Cookie("Id")
		number, _ := c.Cookie("number")
		url := c.Request.URL.String()
		c.Request.Header.Set("Authorization", Token)
		var urlList = []string{
			"/login",
			"/403",
			"/404",
			"/exit",
		}
		if Token == "" {
			if in(url, []string{"/login"}) {
				c.Next()
			} else {
				c.Redirect(http.StatusMovedPermanently, "/login")
				return
			}
		} else {
			if in(url, urlList) {
				return
			}
			_, claims1, _ := login.ParseToken(Token) //解析token
			if claims1.StuName != Name || claims1.Number != number || claims1.Id != Id {
				println("登入信息错误")
				c.Redirect(http.StatusMovedPermanently, "/login")
				return
			}
			publicurl, _ := regexp.MatchString("/public.*", url)
			if !publicurl {
				if !RouteIsolation(claims1.Status, url) {
					c.Redirect(http.StatusMovedPermanently, "/403")
					c.JSON(200, gin.H{
						"msg": 123,
					})
				}
			}
			c.Next()
		}
	}
}

// RouteIsolation 老师学生路由隔离
func RouteIsolation(Status string, url string) bool {
	var Sta string
	teaurl, _ := regexp.MatchString("/teacher.*", url)
	if teaurl {
		Sta = "老师"
	} else {
		Sta = "学生"
	}
	if Sta != Status {
		return false
	}
	return true
}
